ASP.Net Validation - CustomValidator

If any of the other legalists can help you, CustomValidator can usually do this, it is not a predefined way of doing the work; You write the code to validate your self, it is absolutely powerful, because the possibilities are basically endless. A common way to use CustomValidator is to look for a database to see if the value is valid or not. Since this tutorial has not yet coded database access, we will do a simple example, but hopefully you can do everything with custom volunteer. Control allows you to validate both clientide and server side, where the server side approach is probably the most powerful. Of course, to validate server-side validation, a postback is required, but in most cases, it really is not a problem is

In this example, we will only examine the length of the string in the text box. This is a very basic and useful example, only you have been shown how you can use CustomValidator.


Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />

As you can see, it is very simple, only the unknown property is an onservervalidate event. This codeBehind is used to refer to a method that will handle verification. Switch to our CodeBehind file and add the following method:


protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}

It is very simple; the validator basically works by setting the e.IsValid Boolean value in true or false form. Here we e Verify the valve, which is the string of control that is being validated, because its length. If it is actually 8 letters long, then we withdraw the truth, otherwise we make false return.